package simbot.example.task;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.RequiredArgsConstructor;
import love.forte.simbot.Identifies;
import love.forte.simbot.application.Application;
import love.forte.simbot.component.mirai.MiraiGroup;
import love.forte.simbot.component.mirai.bot.MiraiBot;
import love.forte.simbot.component.mirai.bot.MiraiBotManager;
import love.forte.simbot.component.mirai.message.MiraiSendOnlyImage;
import love.forte.simbot.definition.Group;
import love.forte.simbot.message.MessagesBuilder;
import love.forte.simbot.resources.Resource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import simbot.example.entity.*;
import simbot.example.mapper.GroupQuMapper;
import simbot.example.mapper.MessageLogMapper;
import simbot.example.mapper.ParamMapper;
import simbot.example.mapper.SaoHuaMapper;
import simbot.example.util.HttpUtil;
import simbot.example.util.QuFuUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ForteScarlet
 */
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MessageSendTask {

    /**
     * simbot启动后得到的 {@link Application}.
     */
    private final Application application;

    /**
     * 定时任务
     */
    // @Scheduled(cron = "0/20 * * * * ?")
    // public void task3() throws IOException {
    //     for (var botManager : application.getBotManagers()) {
    //         // 寻找到所需的botManager。例如 MiraiBotManager
    //         if (botManager instanceof MiraiBotManager miraiBotManager) {
    //             // 得到你想要的bot，例如列表中第一个bot
    //             MiraiBot miraiBot = miraiBotManager.all().get(0);
    //             String gourid="719793954";
    //             // Integer integer = Integer.valueOf(gourid);
    //             MiraiGroup group = miraiBot.getGroup(Identifies.ID(integer));
    //             group.sendBlocking("你好啊");
    //             group.sendAsync("你好啊2");
    //
    //
    //         }
    //     }
    //
    // }

    /**
     * 定时任务
     */
    // @Scheduled(cron = "0/30 * * * * ?")
    // public void task() throws IOException {
    //     for (var botManager : application.getBotManagers()) {
    //         // 寻找到所需的botManager。例如 MiraiBotManager
    //         if (botManager instanceof MiraiBotManager miraiBotManager) {
    //             // 得到你想要的bot，例如列表中第一个bot
    //             final var miraiBot = miraiBotManager.all().get(0);
    //             //获取mybatis
    //             String resource = "mybatis-config.xml";
    //             InputStream inputStream = Resources.getResourceAsStream(resource);
    //             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //
    //             //2. 获取SqlSession对象，用它来执行sql
    //             SqlSession sqlSession = sqlSessionFactory.openSession();
    //             //3. 获取mapper
    //             GroupQuMapper mapper = sqlSession.getMapper(GroupQuMapper.class);
    //             MessageLogMapper messageLogMapper = sqlSession.getMapper(MessageLogMapper.class);
    //             List<GroupQu> groupQus = mapper.selectAll();
    //
    //             Map<String, List<GroupQu>> collect1 = groupQus.stream().collect(Collectors.groupingBy(p -> p.getQu(), Collectors.toList()));
    //             Set<String> fuList = collect1.keySet();
    //             for (String fu : fuList) {
    //                 Param param = QuFuUtil.getParam("zhuama");
    //                 String url = param.getValue() + "?pageIndex=1&pageSize=50&server=" + fu + "&type=horse";
    //                 String result = HttpUtil.get(url);
    //                 final JSONObject json = JSONObject.parseObject(result);
    //                 String data = json.getString("data");
    //                 final JSONObject json1 = JSONObject.parseObject(data);
    //                 String list = json1.getString("list");
    //                 List<ZhuaMaDto> zhuaMaDtoList = (List<ZhuaMaDto>) JSONArray.parseArray(list, ZhuaMaDto.class);
    //
    //                 String message = "";
    //                 //获取时间戳(十分钟前的)
    //                 long time = System.currentTimeMillis() - 60000 * 11;
    //                 List<ZhuaMaDto> collect = zhuaMaDtoList.stream().filter(p -> "zhcn_hd".equals(p.getEdition()) && p.getTime() * 1000 > time).collect(Collectors.toList());
    //                 //5-10分钟播报
    //                 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    //                 for (ZhuaMaDto zhuaMaDto : collect) {
    //                     MessageLog messageLog = messageLogMapper.selectById(zhuaMaDto.getId());
    //                     if (ObjectUtil.isNotEmpty(messageLog)) {
    //                         continue;
    //                     } else {
    //                         MessageLog messageLog1 = new MessageLog();
    //                         messageLog1.setId(UUID.randomUUID().toString());
    //                         messageLog1.setMessageId(zhuaMaDto.getId());
    //                         messageLog1.setCreatedOn(new Date());
    //                         messageLogMapper.insertMessageLog(messageLog1);
    //                         long startTime = zhuaMaDto.getTime() * 1000 + 60000 * 5;
    //                         long endTime = zhuaMaDto.getTime() * 1000 + 60000 * 10;
    //                         String start = sdf.format(new Date(Long.parseLong(String.valueOf(startTime))));
    //                         String end = sdf.format(new Date(Long.parseLong(String.valueOf(endTime))));
    //                         String str = zhuaMaDto.getContent();
    //                         String address = str.substring(str.indexOf("有宝马良驹在") + 6, str.lastIndexOf("出没！"));
    //                         message = message + address + "将有宝马良良驹出现   " + start + "~" + end + "\n";
    //                         sqlSession.commit();
    //                     }
    //                 }
    //                 if (!ObjectUtils.isEmpty(message)) {
    //                     for (GroupQu groupQu : collect1.get(fu)) {
    //                         String groupId = groupQu.getGroupId();
    //                         Integer integer = Integer.valueOf(groupId);
    //                         MiraiGroup group = miraiBot.getGroup(Identifies.ID(integer));
    //                         group.sendBlocking(message);
    //
    //                     }
    //                 }
    //
    //             }
    //             sqlSession.close();
    //         }
    //     }
    // }


    /**
     * 早报定时任务
     */
    @Scheduled(cron = "0 0 9 * * ?")
    public void task2() throws IOException {
        for (var botManager : application.getBotManagers()) {
            // 寻找到所需的botManager。例如 MiraiBotManager
            if (botManager instanceof MiraiBotManager miraiBotManager) {
                // 得到你想要的bot，例如列表中第一个bot
                final var miraiBot = miraiBotManager.all().get(0);
                Param zaobao = QuFuUtil.getParam("zaobao");
                Param moyu = QuFuUtil.getParam("moyu");
                Param zaobaotoken = QuFuUtil.getParam("zaobaotoken");
                //获取mybatis
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

                //2. 获取SqlSession对象，用它来执行sql
                SqlSession sqlSession = sqlSessionFactory.openSession();
                //3. 获取mapper
                //3. 获取mapper
                SaoHuaMapper mapper = sqlSession.getMapper(SaoHuaMapper.class);
                SaoHua saoHua = mapper.selectByRandom();
                GroupQuMapper mapper1 = sqlSession.getMapper(GroupQuMapper.class);
                List<GroupQu> groupQus = mapper1.selectAllzaobao();
                sqlSession.close();
                String s = HttpUtil.get(zaobao.getValue() + "?token=" + zaobaotoken.getValue() + "&format=json");
                final JSONObject json = JSONObject.parseObject(s);
                String data = json.getString("data");
                if (!ObjectUtils.isEmpty(data)) {
                    final JSONObject json1 = JSONObject.parseObject(data);
                    String url = json1.getString("image");
                    // 构建图片
                    MiraiSendOnlyImage offlineImage = MiraiSendOnlyImage.of(Resource.of(new URL(url)));
                    MiraiSendOnlyImage offlineImage1 = MiraiSendOnlyImage.of(Resource.of(new URL(moyu.getValue())));
                    for (GroupQu groupQu : groupQus) {
                        MiraiGroup group = miraiBot.getGroup(Identifies.ID(Integer.valueOf(groupQu.getGroupId())));
                        MessagesBuilder builder = new MessagesBuilder();
                        builder.append(offlineImage1);
                        builder.append(offlineImage);
                        builder.append(saoHua.getText());
                        group.sendBlocking(builder.build());
                    }
                }
            }

        }
    }
}

